/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.utils.executor;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Peter on 2016/9/7.
 */
public class ExecutorPool {
    private static final int POOL_SIZE = 10;
    private static java.util.concurrent.ExecutorService pool;
    private static Map<String, ExecutorTask> currentTasks;

    /**
     * Return the executor pool.
     *
     * @return ExecutorService
     */
    public static java.util.concurrent.ExecutorService getPool() {
        final int maxPoolSize = 10;
        final long keepAliveTime = 3L;
        final int capacity = 100;
        if (pool == null) {
            pool = new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(capacity));
        }
        if (pool.isShutdown()) {
            pool = new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(capacity));
        }
        return pool;
    }

    /**
     * Submit the task to ExecutorService pool.
     *
     * @param task task instance.
     */
    public static void submit(ExecutorTask task) {
        getPool().submit(task);
        getTasks().put(task.getName(), task);
    }

    /**
     * Return tasks in pool.
     *
     * @return Map of task.
     */
    public static Map<String, ExecutorTask> getTasks() {
        if (currentTasks == null) {
            currentTasks = new ConcurrentHashMap<String, ExecutorTask>();
        }
        return currentTasks;
    }
    /**
     * Return tasks in pool by name.
     *
     * @param name task name.
     * @return ExecutorTask.
     */
    public static ExecutorTask getTask(String name) {
        return getTasks().get(name);
    }

    /**
     * Shut down now.
     */
    public static void shutDownNow() {
        ExportThreadManager exportThreadManager = ExportThreadManager.getExportThreadManager();
        exportThreadManager.interruptAllExport();
        getPool().shutdownNow();
    }
}
